package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableLoanSubmitRepayRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TagLoanSubmitRepayRecord {
    public long uid;
    public int last_repay_success_time;

    public static Logger LOG = LoggerFactory.getLogger(TagLoanSubmitRepayRecord.class);

    public TagLoanSubmitRepayRecord() {}

    public TagLoanSubmitRepayRecord(long uid, int last_repay_success_time) {
        this.uid = uid;
        this.last_repay_success_time = last_repay_success_time;
    }

    public long getUid() {
        return uid;
    }

    public int getLast_repay_success_time() {
        return last_repay_success_time;
    }

    public static TagLoanSubmitRepayRecord init(long uid) {
        return new TagLoanSubmitRepayRecord(uid, Integer.MIN_VALUE);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableLoanSubmitRepayRecord.QUERYSQL);
        DataStream<Tuple2<Boolean, TableLoanSubmitRepayRecord>> inputStream =
                tableEnv.toRetractStream(tableRes, TableLoanSubmitRepayRecord.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableLoanSubmitRepayRecord>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableLoanSubmitRepayRecord> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagLoanSubmitRepayRecord-filter")
                        .keyBy(
                                new KeySelector<
                                        Tuple2<Boolean, TableLoanSubmitRepayRecord>, Long>() {
                                    @Override
                                    public Long getKey(
                                            Tuple2<Boolean, TableLoanSubmitRepayRecord> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(new LoanSubmitRepayRecordFlatMapFunction())
                        .uid("TagLoanSubmitRepayRecord-flatmap");
        return out;
    }

    private static class LoanSubmitRepayRecordFlatMapFunction
            extends RichFlatMapFunction<Tuple2<Boolean, TableLoanSubmitRepayRecord>, String> {
        ValueState<TagLoanSubmitRepayRecord> loanSubmitRepayRecordVState;

        @Override
        public void open(Configuration parameters) throws Exception {
            loanSubmitRepayRecordVState =
                    getRuntimeContext()
                            .getState(
                                    new ValueStateDescriptor<TagLoanSubmitRepayRecord>(
                                            "loanSubmitRepayRecordVState",
                                            TagLoanSubmitRepayRecord.class));
        }

        @Override
        public void flatMap(
                Tuple2<Boolean, TableLoanSubmitRepayRecord> input, Collector<String> out)
                throws Exception {

            long uid = input.f1.getUid();
            int create_time = (int) (input.f1.getCreate_time().getTime() / 1000);

            TagLoanSubmitRepayRecord tempRecordTag = loanSubmitRepayRecordVState.value();
            TagLoanSubmitRepayRecord curRecordTag =
                    tempRecordTag == null ? TagLoanSubmitRepayRecord.init(uid) : tempRecordTag;
            try {
                if (create_time > curRecordTag.getLast_repay_success_time()) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("uid", uid);
                    jsonObject.put("last_repay_success_time", create_time);
                    out.collect(jsonObject.toString());

                    curRecordTag.last_repay_success_time = create_time;
                    loanSubmitRepayRecordVState.update(curRecordTag);
                }
            } catch (Exception e) {
                LOG.warn("Exception date is: " + input.f1.toString());
                e.printStackTrace();
            }
        }
    }
}
